package com.powerbank.gateway.config;

import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.cloud.gateway.filter.ratelimit.KeyResolver;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Component;
import reactor.core.publisher.Mono;

import java.util.List;

/**
 * 网关配置类
 */
@Configuration
public class GatewayConfig {

    /**
     * IP限流键解析器
     */
    @Bean("ipKeyResolver")
    public KeyResolver ipKeyResolver() {
        return exchange -> {
            String clientIp = "";
            if (exchange.getRequest().getRemoteAddress() != null && 
                exchange.getRequest().getRemoteAddress().getAddress() != null) {
                clientIp = exchange.getRequest().getRemoteAddress().getAddress().getHostAddress();
            }
            return Mono.just(clientIp);
        };
    }

    /**
     * 用户限流键解析器
     */
    @Bean("userKeyResolver")
    public KeyResolver userKeyResolver() {
        return exchange -> {
            String userId = exchange.getRequest().getHeaders().getFirst("X-User-Id");
            return Mono.just(userId != null ? userId : "anonymous");
        };
    }

    /**
     * 路径限流键解析器
     */
    @Bean("pathKeyResolver")
    public KeyResolver pathKeyResolver() {
        return exchange -> Mono.just(exchange.getRequest().getPath().value());
    }

    /**
     * 网关配置属性
     */
    @Component("gatewayConfig")
    @ConfigurationProperties(prefix = "powerbank.gateway.auth")
    public static class GatewayConfigProperties {
        
        /**
         * 白名单路径
         */
        private List<String> whiteList;
        
        /**
         * JWT密钥
         */
        private String jwtSecret;
        
        /**
         * Token过期时间
         */
        private Long tokenExpire;
        
        public List<String> getWhiteList() {
            return whiteList;
        }
        
        public void setWhiteList(List<String> whiteList) {
            this.whiteList = whiteList;
        }
        
        public String getJwtSecret() {
            return jwtSecret;
        }
        
        public void setJwtSecret(String jwtSecret) {
            this.jwtSecret = jwtSecret;
        }
        
        public Long getTokenExpire() {
            return tokenExpire;
        }
        
        public void setTokenExpire(Long tokenExpire) {
            this.tokenExpire = tokenExpire;
        }
    }
}